<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="header-left">
          <img src="../images/logo.png" alt="logo" id="logo" />
          <span>首页</span>
          <span @click="goMyMusic">我的音乐</span>
          <span @click="goFindMusic">发现音乐</span>
        </div>
        <div class="header-right">
          <input
            type="text"
            id="search-input"
            placeholder="搜索音乐"
            v-model="searchKeyword"
          />
          <el-button @click="searchMusic">搜索</el-button>
          <div class="login-register" v-if="!ifLogin">
            <span @click="dialogFormVisible = true"> 登录 </span>
            <span @click="goToRegister">注册</span>
          </div>
          <div class="user-info" v-else>
            <el-dropdown placement="bottom">
              <img src="../images/logo.png" alt="" />

              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item @click="goUserInfo"
                    >个人中心</el-dropdown-item
                  > -->
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div class="user-info-name">{{ userInfo.userInfoname }}</div>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-dialog v-model="dialogFormVisible" title="登录" width="500">
          <el-form :model="form">
            <el-form-item label="账号" :label-width="formLabelWidth">
              <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input
                v-model="form.password"
                autocomplete="off"
                type="password"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button
                type="primary"
                @click="(dialogFormVisible = false), confirmLogin()"
              >
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>
        <div class="Carousel">
          <div class="block text-center">
            <el-carousel height="600px">
              <el-carousel-item>
                <img src="../images/Carousel1.png" alt="" />
              </el-carousel-item>
              <el-carousel-item>
                <img src="../images/Carousel2.png" alt="" />
              </el-carousel-item>
              <el-carousel-item>
                <img src="../images/Carousel3.png" alt="" />
              </el-carousel-item>
              <el-carousel-item>
                <img src="../images/Carousel4.png" alt="" />
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div class="Recommended">
          <div class="recommended-title">歌单推荐</div>

          <div class="block text-center" id="recommended-carousel">
            <el-carousel height="500px">
              <el-carousel-item>
                <div
                  v-for="(item, index) in recommendations1"
                  :key="index"
                  @click="goPlaylistDetail(item)"
                >
                  <img :src="item.recommendImage" alt="" />
                  <span>{{ item.recommendTitle }}</span>
                  <br />
                  <span>{{ item.recommendData }}</span>
                </div>
              </el-carousel-item>
              <el-carousel-item>
                <div
                  v-for="(item, index) in recommendations2"
                  :key="index"
                  @click="goPlaylistDetail(item)"
                >
                  <img :src="item.recommendImage" alt="" />
                  <span>{{ item.recommendTitle }}</span>
                  <br />
                  <span>{{ item.recommendData }}</span>
                </div>
              </el-carousel-item>
              <el-carousel-item>
                <div
                  v-for="(item, index) in recommendations3"
                  :key="index"
                  @click="goPlaylistDetail(item)"
                >
                  <img :src="item.recommendImage" alt="" />
                  <span>{{ item.recommendTitle }}</span>
                  <br />
                  <span>{{ item.recommendData }}</span>
                </div>
              </el-carousel-item>
              <el-carousel-item>
                <div
                  v-for="(item, index) in recommendations4"
                  :key="index"
                  @click="goPlaylistDetail(item)"
                >
                  <img :src="item.recommendImage" alt="" />
                  <span>{{ item.recommendTitle }}</span>
                  <br />
                  <span>{{ item.recommendData }}</span>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div class="ranking-list">
          <div class="ranking-title">排行榜</div>
          <div class="ranking-content">
            <div>
              <span>巅峰榜</span>
              <span>热歌</span>
              <span
                class="ranking-song-list"
                v-for="(item, index) in hotranking"
                :key="index"
                @click="goMusicDetail(item)"
              >
                {{ item.songtitle }} -- {{ item.songauthor }}</span
              >
            </div>
            <div>
              <span>巅峰榜</span>
              <span>怀旧</span>
              <span
                class="ranking-song-list"
                v-for="(item, index) in oldranking"
                :key="index"
                @click="goMusicDetail(item)"
              >
                {{ item.songtitle }} -- {{ item.songauthor }}</span
              >
            </div>
            <div>
              <span>巅峰榜</span>
              <span>欧美</span>
              <span
                class="ranking-song-list"
                v-for="(item, index) in europeranking"
                :key="index"
                @click="goMusicDetail(item)"
              >
                {{ item.songtitle }} -- {{ item.songauthor }}</span
              >
            </div>
            <div>
              <span>巅峰榜</span>
              <span>韩国</span>
              <span
                class="ranking-song-list"
                v-for="(item, index) in korearanking"
                :key="index"
                @click="goMusicDetail(item)"
              >
                {{ item.songtitle }} -- {{ item.songauthor }}</span
              >
            </div>
            <div>
              <span>巅峰榜</span>
              <span>华语</span>
              <span
                class="ranking-song-list"
                v-for="(item, index) in newranking"
                :key="index"
                @click="goMusicDetail(item)"
              >
                {{ item.songtitle }} -- {{ item.songauthor }}</span
              >
            </div>
          </div>
        </div>
        <div class="MV-list">
          <div class="MV-title">MV推荐</div>
          <el-carousel height="650px">
            <el-carousel-item>
              <div
                v-for="(item, index) in mvlist"
                :key="index"
                @click="goMvDetail(item)"
              >
                <img :src="item.mvImg" alt="" />
                <span>{{ item.mvtitle }}</span
                ><br />
                <span>{{ item.mvauthor }}</span>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="other-list">
          <div>
            服务条款| 隐私政策| 儿童隐私政策| 版权投诉| 投资者关系| 广告合作 |
            联系我们
          </div>
          <div>洛阳职业技术学院 | 23级软件309班 | 杨震</div>
        </div>
      </el-main>
    </el-container>
  </div>
  <div v-if="ifLogin && isAdmin" class="admin-float-btn">
    <router-link to="/admin" class="admin-btn">
      <i class="el-icon-s-tools"></i>
      <span>管理后台</span>
    </router-link>
  </div>
</template>

<script setup>
import axios from "axios";
import { ElMessage } from "element-plus";

import { reactive, ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";

const $router = useRouter();

// 管理员状态
const isAdmin = ref(false);

// 登录状态
const ifLogin = ref(false);
const dialogFormVisible = ref(false);
const userInfo = ref({
  userID: "",
  userInfoname: "",
  userToken: "",
  is_admin: false,
});

const form = reactive({
  username: "",
  password: "",
});

// 搜索关键词
const searchKeyword = ref("");

// 数据列表
const mvlist = ref([]);
const hotranking = ref([]);
const oldranking = ref([]);
const europeranking = ref([]);
const korearanking = ref([]);
const newranking = ref([]);
const recommendations1 = ref([]);
const recommendations2 = ref([]);
const recommendations3 = ref([]);
const recommendations4 = ref([]);

const formLabelWidth = ref("120px");

// 登录方法
// 修改后的登录方法
const confirmLogin = async () => {
  try {
    const response = await axios.post("http://localhost:3001/api/login", {
      username: form.username,
      password: form.password,
    });

    console.log("登录响应:", response.data); // 打印后端返回的数据

    if (response.data.user) {
      const { user } = response.data;

      // 映射后端字段到前端期望的格式
      const normalizedUser = {
        userID: user.id, // 后端返回 id，映射到前端 userID
        userInfoname: user.username, // 后端返回 username，映射到前端 userInfoname
        userToken: user.token, // 后端返回 token，映射到前端 userToken
        is_admin: user.is_admin === 1, // 转换数字为布尔值
      };

      // 保存到本地存储
      localStorage.setItem("userID", normalizedUser.userID);
      localStorage.setItem("userToken", normalizedUser.userToken);
      localStorage.setItem("userInfoname", normalizedUser.userInfoname);
      localStorage.setItem("is_admin", normalizedUser.is_admin ? "1" : "0");

      // 更新状态
      ifLogin.value = true;
      userInfo.value = normalizedUser;
      isAdmin.value = normalizedUser.is_admin;

      ElMessage.success("登录成功");
    }
  } catch (error) {
    console.error("登录错误:", error);
    ElMessage.error("登录失败，请检查账号密码");
  }
};
// 退出登录
const logout = () => {
  ifLogin.value = false;
  isAdmin.value = false;
  userInfo.value = {
    userID: "",
    userInfoname: "",
    userToken: "",
    is_admin: false,
  };

  // 清除本地存储
  localStorage.removeItem("userID");
  localStorage.removeItem("userToken");
  localStorage.removeItem("userInfoname");
  localStorage.removeItem("is_admin");

  ElMessage.success("退出登录成功");
};

// 初始化数据和状态
onMounted(async () => {
  // 加载数据
  await loadData();

  // 检查登录状态
  const userID = localStorage.getItem("userID");
  const userToken = localStorage.getItem("userToken");
  const userInfoname = localStorage.getItem("userInfoname");
  const is_admin = localStorage.getItem("is_admin"); // 字符串 "1" 或 "0"

  if (userID && userToken && userInfoname) {
    ifLogin.value = true;
    userInfo.value = {
      userID,
      userInfoname,
      userToken,
      is_admin: is_admin === "1", // 转为布尔值
    };
    isAdmin.value = userInfo.value.is_admin;
  } else {
    ifLogin.value = false;
    isAdmin.value = false;
  }

  // 监听localStorage变化
  window.addEventListener("storage", handleStorageChange);
});

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener("storage", handleStorageChange);
});

// 存储变化监听
const handleStorageChange = () => {
  const userID = localStorage.getItem("userID");
  const userToken = localStorage.getItem("userToken");
  const userInfoname = localStorage.getItem("userInfoname");
  const is_admin = localStorage.getItem("is_admin");

  if (userID && userToken && userInfoname) {
    ifLogin.value = true;
    userInfo.value = {
      userID,
      userInfoname,
      userToken,
      is_admin: is_admin === "1",
    };
    isAdmin.value = userInfo.value.is_admin;
  } else {
    ifLogin.value = false;
    isAdmin.value = false;
  }
};

// 数据加载方法
const loadData = async () => {
  // MV数据
  try {
    const response = await axios.get("http://localhost:3001/api/mvlist");
    mvlist.value = response.data;
  } catch (error) {
    console.error("MV数据获取失败:", error);
  }

  // 排行榜数据
  try {
    const response = await axios.get("http://localhost:3001/api/newranking");
    newranking.value = response.data;
  } catch (error) {
    console.error("新歌榜数据获取失败:", error);
  }
  try {
    const response = await axios.get("http://localhost:3001/api/korearanking");
    korearanking.value = response.data;
  } catch (error) {
    console.error("韩国榜数据获取失败:", error);
  }
  try {
    const response = await axios.get("http://localhost:3001/api/europeranking");
    europeranking.value = response.data;
  } catch (error) {
    console.error("欧美榜数据获取失败:", error);
  }
  try {
    const response = await axios.get("http://localhost:3001/api/oldranking");
    oldranking.value = response.data;
  } catch (error) {
    console.error("怀旧榜数据获取失败:", error);
  }
  try {
    const response = await axios.get("http://localhost:3001/api/hotranking");
    hotranking.value = response.data;
  } catch (error) {
    console.error("热歌榜数据获取失败:", error);
  }

  // 推荐歌单数据
  try {
    const response = await axios.get("http://localhost:3001/api/recommended");
    const allRecommendations = response.data;
    recommendations1.value = allRecommendations.slice(0, 5);
    recommendations2.value = allRecommendations.slice(5, 10);
    recommendations3.value = allRecommendations.slice(10, 15);
    recommendations4.value = allRecommendations.slice(15, 20);
  } catch (error) {
    console.error("推荐歌单数据获取失败:", error);
  }
};

// 路由跳转方法
const goMvDetail = (item) =>
  $router.push({ name: "mv", params: { id: item.ID } });
const goMusicDetail = (item) =>
  $router.push({
    name: "MusicDetail",
    params: {
      id: item.songID,
      songtitle: item.songtitle,
      songauthor: item.songauthor,
    },
  });
const goPlaylistDetail = (item) =>
  $router.push({ name: "playlist", params: { id: item.id } });
const goUserInfo = () => $router.push("/userinfo");
const goFindMusic = () => $router.push("/findmusic");
const goMyMusic = () => $router.push("/mymusic");
const goToRegister = () => $router.push("/register");

// 搜索方法
const searchMusic = () => {
  if (searchKeyword.value.trim()) {
    $router.push({
      path: "/findmusic",
      query: { keyword: searchKeyword.value.trim() },
    });
  } else {
    ElMessage.warning("请输入搜索关键词");
  }
};
</script>

<style scoped>
.admin-float-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 2000;
}

.admin-btn {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
  color: white;
  padding: 12px 20px;
  border-radius: 30px;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.admin-btn i {
  margin-right: 8px;
  font-size: 18px;
}

.admin-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 77, 79, 0.4);
}
/* 修改菜单项背景色和过渡效果 */
:deep(.el-dropdown-menu__item) {
  transition: background-color 0.3s !important;
  color: #1e1e1e !important;
}

/* 修改悬停效果 */
:deep(.el-dropdown-menu__item:hover) {
  background-color: #ff1919 !important;
}

.MV-list .el-carousel .el-carousel__item div img {
  width: 320px;
  height: 200px;
}

.ranking-list .ranking-content .ranking-song-list {
  font-size: 15px;
  margin-top: 20px;
}

.user-info {
  width: 200px;
  height: 50px;
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.user-info img {
  border: none !important;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-left: 20px;
}

.user-info-name {
  display: inline;
  color: white;
  margin-left: 20px;
  font-size: 20px;
}

:deep(.el-dialog) {
  background: #1e1e1e;
  border-radius: 12px;
  border: 1px solid #404040;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  color: #fff !important;
}

:deep(.el-input__wrapper) {
  background: #fff;
  margin-right: 30px;
}

.other-list {
  width: 100%;
  height: 220px;
  background-color: #212121;
}

.other-list div {
  color: white;
  padding-top: 60px;
  text-align: center;
  width: 100%;
  height: 50px;
}

.MV-list .el-carousel .el-carousel__item {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
}

.MV-list .el-carousel .el-carousel__item div {
  width: 290px;
  height: 200px;
  color: white;
}

.MV-title {
  width: 400px;
  height: 50px;
  margin: 0 auto;
  text-align: center;
  font-size: 36px;
  color: #ffffff;
  font-weight: bold;
}

.MV-list {
  width: 100%;
  height: 700px;
  background-color: #1e1e1e;
}

.ranking-content div span {
  text-align: center;
  display: block;
  font-size: 26px;
  color: #ffffff;
}

.ranking-title {
  width: 400px;
  height: 50px;
  margin: 0 auto;
  text-align: center;
  font-size: 36px;
  color: #ffffff;
  font-weight: bold;
}

.ranking-content div {
  background-color: #ff4d4f;
  width: 200px;
  height: 500px;
}

.ranking-content div:hover {
  transition: background-color 0.3s;
  background-color: #ff1919;
}

.ranking-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.ranking-list {
  background-color: #212121;
  height: 600px;
  width: 100%;
}

#recommended-carousel .el-carousel .el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
  justify-content: space-around;
  background-color: #1e1e1e;
}

#recommended-carousel .el-carousel .el-carousel__item div {
  width: 224px;
  height: 224px;
  background-color: blueviolet;
  text-align: center;
  font-size: 18px;
  color: white;
}

#recommended-carousel .el-carousel .el-carousel__item div img {
  width: 224px;
  height: 224px;
}

.Carousel img {
  width: 100%;
  height: 100%;
}

.demonstration {
  color: var(--el-text-color-secondary);
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #1e1e1e;
}

.recommended-list {
  display: flex;
  justify-content: space-around;
}

.recommended-list div {
  width: 224px;
  height: 224px;
}

.recommended-list div img {
  width: 224px;
  height: 224px;
}

.recommended-list div span {
  color: white;
  margin-top: 20px;
  text-align: center;
}

.recommended-title {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36px;
  font-weight: bold;
}

/* 添加以下样式覆盖默认边距 */
.el-main {
  padding: 0 !important;
}

.el-header {
  background-color: black;
  height: 140px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  font-size: 24px;
  padding: 0 20px;
}

#logo {
  width: 140px;
  height: 140px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left span {
  margin-left: 20px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.header-left span:hover {
  background-color: #333;
  border-radius: 5px;
  color: #ff1919;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right input {
  width: 300px;
  height: 40px;
  margin-right: 20px;
  padding: 0 20px;
  font-size: 18px;
  border: none;
  border-radius: 20px;
  background-color: #1e1e1e;
  color: white;
  outline: none;
  transition: background-color 0.3s;
}

.header-right input:focus {
  background-color: #333;
}

.header-right .el-button {
  height: 40px;
  padding: 0 20px;
  border: none;
  border-radius: 20px;
  background-color: #ff4d4f;
  transition: background-color 0.3s;
  color: #ffffff;
}

.header-right .el-button:hover {
  background-color: #ff1919;
}

.header-right span {
  margin-left: 20px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.header-right span:hover {
  background-color: #333;
  border-radius: 5px;
  color: #ff1919;
}

.Carousel {
  height: 600px;
  width: 100%;
}

.Recommended {
  background-color: #1e1e1e;
  height: 600px;
  width: 100%;
}
</style>
